<script setup lang="ts">
import { deleteAddressApi, getAddressApi, putAddressApi, setDefaultAddress } from '@/api/address'
import { pageUrl } from '@/utils/constants'
import { useAddressStore } from '@/stores/modules/address'
import type { addressItem } from '@/types/address'
import { onShow } from '@dcloudio/uni-app'
import { nextTick, ref } from 'vue'
import { add, debounce } from 'lodash'
import type { waitForDebugger } from 'node:inspector'

const props = defineProps<{
  noOk: boolean
}>()

const addressStore = useAddressStore()
// eslint-disable-next-line no-undef
const paging = ref<ZPagingInstance>()
const addressList = ref<addressItem[]>([])
const queryList = (page: number, page_size: number) => {
  getAddressApi({
    page,
    page_size,
  }).then((res) => {
    paging.value?.complete(res.result.data)
  })
}

onShow(() => {
  isShowSetting.value = false
  nextTick(() => {
    paging.value?.reload()
  })
})

//复制地址
const copyAddress = (item: addressItem) => {
  const addressText = `${item.name} ${item.phone} ${item.full_location}`
  uni.setClipboardData({
    data: addressText,
    success: () => {
      uni.showToast({
        title: 'Address copied successfully',
        icon: 'success'
      })
    }
  })
}

//删除地址
const deleteAddress = (id: string | number) => {
  deleteAddressApi(id).then((res) => {
    addressList.value.splice(
      addressList.value.findIndex((item) => item.id == id),
      1,
    )
  })
  if (addressStore.selectedAddress?.id == id) {
    addressStore.clearSelectedAddress()
  }
  setTimeout(() => {
    uni.showToast({
      icon: 'success',
      title: 'Deleted successfully',
    })
  }, 1000)
}

const selectAddress = ref({})
const selectAddressHandler = (item: addressItem) => {
  selectAddress.value = item
}

//选中收货地址
const onSelectedAddress = () => {
  if (addressStore.scene === 'order') {
    addressStore.changeSelectedAddress(selectAddress.value || {})
    uni.navigateBack()
  }
}

//修改选中状态
const onChangeSelected = debounce((item: any) => {
  console.log(item)
  setDefaultAddress({id: item.id})
  queryList(1, 10)
}, 500)

const setDefault = async (item: addressItem) => {
  await putAddressApi({
    ...item,
    is_default: 1,
  })
  addressStore.changeSelectedAddress(item)
  paging.value?.reload()
  uni.showToast({
    icon: 'success',
    title: 'Set successfully',
  })
}

let isShowSetting = ref(false)

const toAdd = () => {
  uni.navigateTo({
    url: `${pageUrl['address-form']}`,
  })
}

const gotoEditAddress = (id: string | number) => {
  uni.navigateTo({
    url: `${pageUrl['address-form']}?id=${id}`,
  })
}

onShow(() => {
  selectAddress.value = {}
})


</script>

<template>
  <view>
    <view class="cart-operate">
      <view class="title">
        <!-- <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator> -->
        Delivery address</view>
      <view class="setting">
        <view class="operate-item" v-if="!isShowSetting" @tap="isShowSetting = true">
          <uni-icons type="tune" size="18" color="#ff5f3c"></uni-icons>
          <view>Management</view>
        </view>
        <view class="operate-item" v-if="!isShowSetting" @tap="toAdd">
          <uni-icons type="plusempty" size="18" color="#ff5f3c"></uni-icons>
          <view>New address</view>
        </view>
        <template v-if="isShowSetting">
          <view class="operate-item" @tap="isShowSetting = false">
            <uni-icons type="close" size="18" color="#ff5f3c"></uni-icons>
            <view>Exit</view>
          </view>
        </template>
      </view>
    </view>
    <shop-paginate-list class="viewport" ref="paging" v-model="addressList" @query="queryList" :options="{
      auto: false,
      emptyViewText: 'There is no delivery address for the time being',
    }">
      <view class="address" v-if="addressList.length > 0">
        <uni-swipe-action class="address-list">
          <uni-swipe-action-item v-for="item in addressList" :key="item.id" class="address-item" :style="{'background-color': (item.id === selectAddress.id && !noOk) ? '#fff7f4' : ''}">
            <view class="item" @tap="selectAddressHandler(item)">
              <!-- @tap="onSelectedAddress(item)" -->
              <view class="item-content">
                <view class="locate">{{ item.full_location }}
                  <text v-if="item.is_default" class="badge">Default</text>
                </view>
                <view class="locate-address">
                  <view class="address-detail">
                    {{ item.city }}
                  </view>
                  <!-- <navigator class="edit" hover-class="none" :url="`${pageUrl['address-form']}?id=${item.id}`"
                    @tap.stop="() => { }" @tap.prevent="() => { }"> -->
                  <uni-icons @tap="gotoEditAddress(item.id)" type="compose" size="24"></uni-icons>
                  <!-- </navigator> -->
                </view>
                <view class="user">
                  {{ item.name }}
                  <text class="contact">{{ item.phone }}</text>
                </view>
              </view>
              <view class="button-group">
                <view class="set-default">
                  <template v-if="isShowSetting">
                    <text class="checkbox" :class="{ checked: item.is_default === 1 }"
                      @tap.stop="onChangeSelected(item)"></text><text class="mr">Default</text>
                  </template>
                </view>
                <view class="button" v-if="isShowSetting">
                  <text @tap="deleteAddress(item.id)" class="delete-button">Delete</text>
                  <text @tap="copyAddress(item)" class="default-button">Copy</text>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <template #bottom>
        <!-- <shop-submit-button title="新建地址" @tap="toAdd" /> -->
         <view class="bottom-container" v-if="!noOk">
          <view class="add-btn" @tap="onSelectedAddress">Sure</view>
         </view>
         
      </template>
    </shop-paginate-list>
  </view>
</template>
<style lang="scss" scoped>
page {
  height: 100%;
  overflow: hidden;
}

.cart-operate {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 30rpx 20rpx;
  

  .title {
    font-size: 30rpx;
    font-weight: bold;
    display: flex;
    align-items: center;

    text {
      font-weight: 400;
      font-size: 24rpx;
      margin-left: 4rpx;
    }
  }

  .setting {
    display: flex;
    align-items: center;
  }

  .operate-item {
    font-size: 24rpx;
    margin-right: 20rpx;
    // border-right: 1px solid #e5e5e5;
    // padding-right: 20rpx;
    color: #ff5f3c;
    display: flex;
    align-items: center;

    &:last-child {
      border-right: none;
      margin-right: 0;
    }
  }

}

.delete-button {
  margin-right: 15rpx;
}

.default-button, .delete-button {
  display: inline-block;
  justify-content: center;
  align-items: center;
  padding: 4rpx 20rpx;
  border-radius: 6rpx;
  background-color: #f7f7f8;
}

.button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  display: inline-block;
  text-align: center;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f4f4f4;
  margin-top: 100rpx;
}

.address {
  margin: 20rpx 20rpx;
  border-radius: 10rpx;
  padding-bottom: 160rpx;
  // background-color: #fff;
  // padding: 40rpx 20rpx 40rpx 20rpx;
  // border-bottom: 1rpx solid #ddd;

  .item-content {
    line-height: 1;
    // border-bottom: 1rpx solid #ddd;
    position: relative;
  }

  .address-item {
    background-color: #fff;
    padding: 30rpx 20rpx;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
  }

  .button-group {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .set-default {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #333;

    }

    .button {
      display: flex;
    }

    .set-default {
      position: relative;
      top: 6rpx;
    }

    .checkbox {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40rpx;
      height: 100%;

      &::before {
        content: '\e6cd';
        font-family: 'iconfont' !important;
        font-size: 36rpx;
      }

      &.checked::before {
        content: '\e6cc';
        color: #ff5f3c;
      }
    }

    .mr {
      font-size: 24rpx;
      position: relative;
      top: -2rpx;
    }
  }

  .user {
    font-size: 28rpx;
    margin-bottom: 10rpx;
    color: #333;
    line-height: 1.6;

    .contact {
      padding-left: 20rpx;
      color: #666;
    }
  }

  .locate {
    line-height: 1.6;
    font-size: 26rpx;
    color: #333;

    .badge {
      display: inline-block;
      padding: 0 10rpx;
      margin: 2rpx 0 0 10rpx;
      font-size: 20rpx;
      color: #ff5f3c;
      border-radius: 6rpx;
      background-color: #ffe0d8;
    }
  }

  .locate-address {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .address-detail {
      line-height: 1.8;
      font-size: 30rpx;
      color: #000000;
      font-weight: bolder;
    }

    .edit {
      position: absolute;
      top: 100rpx;
      right: 10rpx;
      padding: 2rpx 0 2rpx 20rpx;
      // border-left: 1rpx solid #666;
      font-size: 26rpx;
      color: #666;
      line-height: 1;
    }

  }
}

.blank {
  margin-top: 300rpx;
  text-align: center;
  font-size: 32rpx;
  color: #888;
}
  
.bottom-container{
  position: fixed;
  bottom: 0;
  background: #fff;
  height: 100rpx;
  width: 100%;
  display: flex;
  align-items: center;
}
.add-btn {
  height: 70rpx;
  width: 100%;
  text-align: center;
  line-height: 70rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 10rpx;
  font-size: 30rpx;
  background-color: #ff5f3c;
  
}
.back{
  margin-right: 10rpx;
}
</style>
